﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;

namespace Noea.Parser
{
    // HtmlDocRegEx parses html as regular expressions by using the RegularExpressions class in .Net.
    public class HTMLDocRegEx : IHTMLDoc
    {
        private string doc;

        public HTMLDocRegEx(string doc)
        {
			this.doc = doc;
        }

        // read-only property. Returns the web page as a string.
        public string Document
        {
            get { return doc; }
        }

        // Returns a list of strings containing the urls of all links to pages on the this site.
        // That is: links to web pages outside this are not included
        public IList GetAllLinks()
        {
			List<string> links = new List<string>();
			string regex = @"<a[\s]+[^>]*?href[\s]?=[\s\""\']+(?<href>.*?)[\""\']+.*?>(?<fileName>[^<]+|.*?‌​)?<\/a>";
			MatchCollection mc = Regex.Matches(doc, regex,  RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);

			foreach (Match m in mc)
				links.Add(m.Groups["href"].Value);

			links.AddRange((List<string>)GetFrameSources());

			return links;
        }

		public IList GetFrameSources()
		{
			IList links = new List<string>();
			string regex = @"<iframe\s*src\s*=\s*[""'](.+?)[""'].+>";
			MatchCollection mc = Regex.Matches(doc, regex, RegexOptions.Singleline);

			foreach (Match m in mc)
				links.Add(m.Groups[1].Value);

			return links;
		}

        // returns true if searchString is found in <body>...</body> in this HTML-document
        public bool Contains(string searchString)
        {
			Match body = Regex.Match(doc, @"<body>\s*(.+?)\s*</body>", RegexOptions.Singleline);

			if (body.Groups[1].Value.Contains(searchString))
				return true;
            
            return false;
        }
    }


}